package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OssProperties;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import com.leyou.dto.AliOssSignatureDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AliAuthServiceImpl implements AliAuthService {
    @Autowired
    private  OSS ossClient;
    @Autowired
    private OssProperties prop;
    @Override
    public AliOssSignatureDTO getAliSignature() {
        try {
            // 过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime ;
            Date expiration = new Date(expireEndTime);
            // 上传策略条件
            PolicyConditions policyConds = new PolicyConditions();
            // 文件大小限制
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            // 文件目录限制
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 对策略加密
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 生成签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            // 准备响应结果

            //封装dto
            return AliOssSignatureDTO.of(prop.getAccessKeyId(),prop.getHost(),encodedPolicy,postSignature,expireEndTime,prop.getDir());
        } catch (Exception e) {
            throw  new LyException(500,"生成授权签名失败");
        }

    }
}
